package cn.tedu.sp02.item.controller;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;


@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    //获取订单商品列表
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        List<Item> items = itemService.getItems(orderId);

        // 随机延迟,90%概率执行延迟
        if (Math.random() <0.9){
            //随机延迟时长: 0-5秒
            long t = new Random().nextInt(5000);
            log.info("延迟时长"+t);
            Thread.sleep(t);
        }
        return JsonResult.build().code(200).data(items);
    }
    /*
    @RequestParam 接收表单提交的名值对参数 k1=v1&k2=v2&k3=v3
    @PathVariable 接收路径参数
    @RequestBody 完整接收客户端提交的http协议体数据
     */
    //减少商品库存
    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumbers(items);
        return JsonResult.build().code(200).msg("减少库存成功");
    }

    //处理浏览器自动请求的图标文件
    @GetMapping("/favicon.ico")
    public void ico(){

    }
}
